﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.ExpertGroups;
using YAPACS.RisServer.Abstractions;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Study;

public class Consultation(IRepository<Exam, Guid> examRepository, IRepository<ExpertGroup, Guid> expertGroupRepository, IExamEventService examEventService)
    : WorkflowBase, IConsultation, ITransientDependency
{
    private readonly IRepository<Exam, Guid> _examRepository = examRepository;
    private readonly IRepository<ExpertGroup, Guid> _expertGroupRepository = expertGroupRepository;
    private readonly IExamEventService _examEventService = examEventService;

    protected async override Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        const string key = "Input";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is Dictionary<string, object> data)
        {
            var _expertGroup = data.GetValueOrDefault("expertGroup") as string;
            var _examIds = data.GetValueOrDefault("examIds")?.Serialize();
            ExpertGroup expertGroup = null;
            bool isConsultation = false;
            if (!string.IsNullOrWhiteSpace(_expertGroup))
            {
                var expertGroupId = Guid.Parse(_expertGroup);
                expertGroup = await _expertGroupRepository.GetAsync(expertGroupId);
                isConsultation = true;
            }
            var examIds = _examIds.Deserialize<List<Guid>>();
            var exams = await _examRepository.GetListAsync(e => examIds.Contains(e.Oid));
            foreach (var exam in exams)
            {
                exam.ExpertGroup = expertGroup;
                exam.IsConsultation = isConsultation;

                if (expertGroup == null)
                {
                    await _examEventService.AddExamEventAsync(exam, "取消会诊");
                }
                else
                {
                    await _examEventService.AddExamEventAsync(exam, "申请会诊");
                }
            }
            return new WorkflowOutput { Success = true, Data = examIds };
        }
        return new WorkflowOutput
        {
            Success = false,
            Error = "未获取到参数"
        };
    }
}
